package com.cvmars.jianyou.api.interceptor;


import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.cvmars.jianyou.api.api.Consts;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.config.MyApp;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.module.model.EventAppExit;
import com.cvmars.jianyou.utils.LogUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.prefs.Preferences;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by zsm on 2017/6/26.
 */

public class TokenInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);

        Headers headers =
                response.headers();
        List<String> cookies = headers.values("Set-Cookie");
        LogUtils.d("cookies :" + cookies);


        for (int i = 0; i < cookies.size(); i++) {

            String session = cookies.get(i);
            if (session != null && session.contains("csrftoken")) {
                String JSESSIONID = session.substring(0, session.indexOf(";"));
                LogUtils.d("csrftoken :" + JSESSIONID);
                if (JSESSIONID != null) {
                    String[] split = JSESSIONID.split("=");
                    if (split.length > 1) {
                        Hawk.put(MyConfig.SP_CACHE_TOKEN, split[1]);
                    }
                }

            }
            if (session != null && session.contains("sessionid")) {

                String JSESSIONID = session.substring(0, session.indexOf(";"));
                LogUtils.d("sessionid :" + JSESSIONID);
                if (JSESSIONID != null) {
                    String[] split = JSESSIONID.split("=");
                    if (split.length > 1) {
                        Hawk.put(MyConfig.SP_CACHE_SESSION, split[1]);
                    }
                }
            }
        }

        LogUtils.d("code :" + response.code());

        //重新登录
        if (response.code() == 403) {

            EventBus.getDefault().post(new EventAppExit(true));
            return response;
        }
//        String token = response.header("csrftoken");
//        String sessionid = response.header("sessionid");
//        LogUtils.d("token :" + token + "sessionid :" + sessionid);
        //这里进行Token 过期处理 根据返回的code
        if (response.code() == 400 || response.code() == 405) {
            Gson gson = new Gson();
            try {
                ResponseBody newResponseBodys = response.peekBody(1024 * 1024);
                String string = newResponseBodys.string();
                HttpResult objectResult = gson.fromJson(string, HttpResult.class);


                if (!TextUtils.isEmpty(objectResult.getDetail())) {
                    Message obtain = Message.obtain();
                    obtain.obj = objectResult.getDetail();
                    handler.sendMessage(obtain);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.obj != null) {
                ToastUtils.show(msg.obj.toString());
            }
        }
    };

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private String getNewToken(String oldtoken) throws IOException {
        // 通过一个特定的接口获取新的token，此处要用到同步的retrofit请求

//        Call<HttpResult<UserInfoManager>> newToken = Api.getInstance().getNewToken(oldtoken);
//        retrofit2.Response<HttpResult<UserInfoManager>> execute = newToken.execute();
//        HttpResult<UserInfoManager> body = execute.body();
//        if (body.isSucc()) {
//            UserInfoManager data = body.getData();
//            if (data != null) {
//                userModel.token = data.token;
//                LogUtils.d("Token_Has_Expired token :" + data.token);
//                op.onLogin(userModel);
//                return data.token;
//            }
//        }
        return "";
    }
}
